﻿app.controller('PeopleCtrl', ['$scope', 'Person', 'toastr', 'people',
    function ($scope, Person, toastr, people) {

        $scope.people = people;
        $scope.edit = new Person();
        $scope.editMode = false;

        $scope.savePerson = function() {
            if ($scope.editMode) {
                $scope.edit.$save(function() {
                    toastr.success('Save ' + $scope.edit.Name + ' success');
                    $scope.edit = new Person();
                    $scope.editMode = false;
                });
            } else {
                $scope.edit.$add(function() {
                    $scope.people.push($scope.edit);
                    toastr.success('Add ' + $scope.edit.Name + ' success');
                    $scope.edit = new Person();
                });
            }
            
        };

        $scope.removePerson = function (person) {
            person.$remove(function() {
                for (var i = 0; i < $scope.people.length; i++) {
                    if ($scope.people[i] === person) {
                        $scope.people.splice(i, 1);
                        toastr.success('Remove ' + person.Name + ' success');
                        return;
                    }
                }
            });
        };

        $scope.editPerson = function(person) {
            if (person) {
                $scope.editMode = true;
                $scope.edit = person;
            }
        };

        $scope.cancelEdit = function() {
            $scope.edit = new Person();
            $scope.editMode = false;
        };

    }]);